﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeTop.复习九月份
{
    public class Solution695_1//全局变量
    {
        private int curCount = 0;

        public int MaxAreaOfIsland(int[][] grid)
        {
            int m = grid.Length;
            int n = grid[0].Length;
            int res = 0;
            for (int i = 0; i < m; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    if (grid[i][j] == 1)//有岛屿，计算面积
                    {
                        DFS(grid, i, j);

                        Console.WriteLine(curCount);
                        res = Math.Max(res, curCount);
                        curCount = 0;
                    }
                }
            }

            return res;
        }

        private int[][] dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];

        private void DFS(int[][] grid, int row, int col)
        {
            int m = grid.Length;
            int n = grid[0].Length;
            grid[row][col] = 0;
            curCount++;

            for (int i = 0; i < 4; i++)
            {
                int nextRow = row + dirs[i][0];
                int nextCol = col + dirs[i][1];
                if (nextRow >= 0 && nextRow < m && nextCol >= 0 && nextCol < n)
                {
                    if (grid[nextRow][nextCol] == 1)
                    {
                        DFS(grid, nextRow, nextCol);
                    }
                }
            }
        }
    }

    public class Solution695//返回值
    {
        private int curCount = 0;

        public int MaxAreaOfIsland(int[][] grid)
        {
            int m = grid.Length;
            int n = grid[0].Length;
            int res = 0;
            for (int i = 0; i < m; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    if (grid[i][j] == 1)//有岛屿，计算面积
                    {
                        int curCount = DFS(grid, i, j);

                        res = Math.Max(res, curCount);
                    }
                }
            }

            return res;
        }

        private int[][] dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];

        private int DFS(int[][] grid, int row, int col)
        {
            int m = grid.Length;
            int n = grid[0].Length;
            grid[row][col] = 0;
            int res = 1;

            for (int i = 0; i < 4; i++)
            {
                int nextRow = row + dirs[i][0];
                int nextCol = col + dirs[i][1];
                if (nextRow >= 0 && nextRow < m && nextCol >= 0 && nextCol < n)
                {
                    if (grid[nextRow][nextCol] == 1)
                    {
                        res += DFS(grid, nextRow, nextCol);
                    }
                }
            }
            return res;
        }
    }
}